package com.caszx.chargingpile.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewStub;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONException;
import com.app.base.app.BaseTopBarDelayActivity;
import com.app.utils.DiskUser;
import com.app.utils.RegularHelper;
import com.app.utils.SystemHelper;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.caszx.chargingpile.utils.ToastHelp;
import com.rey.material.widget.RadioButton;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;

/**注册和忘记密码,重置会员卡密码*/
public class UserSignUpPassWdActivity extends BaseTopBarDelayActivity {

    /**注册*/
    public static  int USER_SIGN_UP = 0;
    /**忘记密码*/
    public static  int USER_MD_PASSWD = 1;
    /**重置会员卡密码*/
    public static  int USER_MD_VIP_CARD = 2;

    private int type ;

    public static  final  int SIGN_IN_RESULT_CODE = 101;
    private  static  int DURATION = 800;
    private int depth = 0;
    private View mViewStep00,mViewStep01,mViewStep02;
    private  int SCREEN_WIDTH;

    //注册第一步:输入手机号
    private RadioButton btn_agree;
    private EditText edit_phone;
    private TextView btn_bind_next_phone;
    private TextView txt_protocol;
    private boolean isChecked = true;
    //注册第二步:验证码
    private TextView time;
    private EditText edit_auth_code;
    private TextView btn_bind_next_auth;
    private RerHandler      _timerHandler;
    private Timer 		    _timer;
    private static Integer  _timerCount = 0;
    private String 			smsid="";

    //注册第三步:输入密码
    private EditText edit_passwd;
    private EditText edit_passwd_confin;
    private TextView btn_bind;

    @Override
    protected void init() {
        type = getIntent().getExtras().getInt("TYPE");
        SCREEN_WIDTH = SystemHelper.getScreenWidth(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_sign_up);
        if(type == USER_MD_PASSWD){
            setCenterTitle(R.string.string_forget_passwd);
        }else if(type == USER_SIGN_UP){
            setCenterTitle(R.string.string_btn_sign_up);
        }else if(type == USER_MD_VIP_CARD){
            setCenterTitle(R.string.string_vip_passwd);
        }
    }

    @Override
    protected void findView() {
        initPhoneView();
    }

    private void initPassWd(){
        if(mViewStep02 == null){
            ViewStub stub = (ViewStub)findViewById(R.id.stubView02);
            mViewStep02 = stub.inflate();
            edit_passwd = (EditText) mViewStep02.findViewById(R.id.edit_passwd);
            edit_passwd_confin = (EditText) mViewStep02.findViewById(R.id.edit_passwd_confin);
            btn_bind = (TextView) mViewStep02.findViewById(R.id.btn_bind);
            if(type == USER_MD_PASSWD){
                btn_bind.setText("提交");
                edit_passwd.setHint("设置密码");
            }else if(type == USER_SIGN_UP){
                btn_bind.setText("完成注册");
            }else if(type == USER_MD_VIP_CARD){
                edit_passwd.setHint("设置密码");
                btn_bind.setText("提交");
            }
            btn_bind.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String passwd = edit_passwd.getText().toString();
                    String passwd_confim = edit_passwd_confin.getText().toString();
                    if(!RegularHelper.checkPassword(passwd, 6, 10)){
                        SnackbarHelp. showSnackbarMsg(UserSignUpPassWdActivity.this,getResources().getString(R.string.regex_passwd_error));
                        return;
                    }
                    if (!passwd.equals(passwd_confim)) {
                        SnackbarHelp. showSnackbarMsg(UserSignUpPassWdActivity.this,getResources().getString(R.string.user_passwd_no_equals));
                        return;
                    }
                    String phone = edit_phone.getText().toString();
                    String code = edit_auth_code.getText().toString();
                    signUp(phone,code,passwd,passwd_confim,smsid);
                    SystemHelper.closeInputFromWindow(UserSignUpPassWdActivity.this);
                }
            });

        }

    }

    private void initAuthView(){
        if(mViewStep01 == null){
            ViewStub stub = (ViewStub)findViewById(R.id.stubView01);
            mViewStep01 = stub.inflate();
            edit_auth_code = (EditText) mViewStep01.findViewById(R.id.edit_auth_code);
            time = (TextView) mViewStep01.findViewById(R.id.time);
            btn_bind_next_auth = (TextView) mViewStep01.findViewById(R.id.btn_bind_next);
            time.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getAuthCode();
                    timerStart();
                }
            });
            btn_bind_next_auth.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String code = edit_auth_code.getText().toString();
                    if(TextUtils.isEmpty(code)){
                        SnackbarHelp.showSnackbarMsg(UserSignUpPassWdActivity.this,"请输入验证码");
                        return;
                    }
                    depth ++;
                    translationX(mViewStep01,0,-SCREEN_WIDTH);
                    initPassWd();
                    translationX(mViewStep02,SCREEN_WIDTH,0);

                }
            });
        }

    }

    private void initPhoneView(){
        if(mViewStep00 == null){
            ViewStub stub = (ViewStub)findViewById(R.id.stubView00);
            mViewStep00 = stub.inflate();
            edit_phone = (EditText) mViewStep00.findViewById(R.id.edit_phone);
            btn_agree = (RadioButton) mViewStep00.findViewById(R.id.btn_agree);
            txt_protocol = (TextView) mViewStep00.findViewById(R.id.txt_protocol);
            btn_bind_next_phone = (TextView) mViewStep00.findViewById(R.id.btn_bind_next);
            if(type == USER_MD_PASSWD||type == USER_MD_VIP_CARD){
                btn_agree.setVisibility(View.GONE);
                txt_protocol.setVisibility(View.GONE);
            }else if(type == USER_SIGN_UP){
                btn_agree.setVisibility(View.VISIBLE);
                txt_protocol.setVisibility(View.VISIBLE);
            }
            txt_protocol.setMovementMethod(LinkMovementMethod.getInstance());
            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append("易威斯用户协议");
            builder.setSpan(new ForegroundColorSpan(Color.parseColor("#FF6CB7FA")),0,builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(false);
                }
                @Override
                public void onClick(View widget) {
                    ToastHelp.showMessage(UserSignUpPassWdActivity.this,"协议");
                }
            };
            builder.setSpan(clickableSpan, 0, builder.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            txt_protocol.setText(builder);
            btn_agree.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(isChecked){
                        isChecked = false;
                        btn_agree.setChecked(false);
                        btn_bind_next_phone.setEnabled(false);
                    }else  {
                        isChecked = true;
                        btn_agree.setChecked(true);
                        btn_bind_next_phone.setEnabled(true);
                    }
                }
            });

            btn_bind_next_phone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String phone = edit_phone.getText().toString();
                    if(!RegularHelper.isMobileNO(phone)){
                        SnackbarHelp.showSnackbarMsg(UserSignUpPassWdActivity.this,"请输入正确的号码");
                        return;
                    }
                    depth ++;
                    translationX(mViewStep00,0,-SCREEN_WIDTH);
                    initAuthView();
                    translationX(mViewStep01,SCREEN_WIDTH,0);
                }
            });
        }
    }



    private void translationX(View view,float start,float end){
        ObjectAnimator objectAnimator = android.animation.ObjectAnimator.ofFloat(view,View.TRANSLATION_X,start,end);
        objectAnimator.setDuration(DURATION);
        objectAnimator.start();
    }

    /**
     * 获取验证码的smsid
     * */
    private void getAuthCode(){
        String phone = edit_phone.getText().toString();
        HashMap<String,String> params = new HashMap<>();
        params.put("phone",phone);
        String url =null;
        if(type == USER_SIGN_UP){
            url = ConstantUrl.URL_SIGIN_UP_AUTH_CODE;
        }else  if(type == USER_MD_PASSWD||type == USER_MD_VIP_CARD){
            url = ConstantUrl.URL_FORGET_PW_CODE;
        }else  if(type == USER_MD_VIP_CARD){
            url = ConstantUrl.URL_USER_RESET_VIP_PASSWD;

        }
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        SnackbarHelp.showSnackbarMsg(UserSignUpPassWdActivity.this,getResources().getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        JSONObject resultJsonObject =  response.optJSONObject("result");
                        if(resultJsonObject!=null){
                            int code =  resultJsonObject.optInt("code");
                            if(code<0){
                                //error
                                 DialogHelp.showDialogOnlyMesg(UserSignUpPassWdActivity.this,resultJsonObject.optString("msg"),null);
                                if(_timerHandler!=null){
                                    _timerHandler.sendEmptyMessage(0);
                                }
                            }else{
                                try {
                                    smsid = response.optString("smsid");
                                }catch (JSONException e){
                                    SnackbarHelp.showSnackbarMsg(UserSignUpPassWdActivity.this,getResources().getString(R.string.error_parser_json));
                                }
                            }
                        }
                    }
                });

    }


    /**
     * 完成注册
     * */
    private void signUp(final String phone, String code, final String pwd, String confirmPwd, String smsid){
        showProgressDialog("提交中");
        HashMap<String,String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this, "token"));
        params.put("code",code);
        params.put("pwd",pwd);
        params.put("confirmPwd", confirmPwd);
        params.put("phone",phone);
        params.put("smsCode", smsid);
        String url = null;
        if(type == USER_SIGN_UP){
            url = ConstantUrl.URL_SIGIN_UP;
        }else  if(type == USER_MD_PASSWD){
            url = ConstantUrl.URL_FORGET_PW;
        }else  if(type == USER_MD_VIP_CARD){
            url = ConstantUrl.URL_USER_RESET_VIP_PASSWD;

        }
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        SnackbarHelp.showSnackbarMsg(UserSignUpPassWdActivity.this,getResources().getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject =  response.optJSONObject("result");
                        if(resultJsonObject!=null){
                            int code =  resultJsonObject.optInt("code");
                            if(code<0){
                                //error
                                 DialogHelp.showDialogOnlyMesg(UserSignUpPassWdActivity.this,resultJsonObject.optString("msg"),null);
                            }else{
                                try {
                                    if(type == USER_SIGN_UP){
                                        //注册成功
                                        Intent intent = getIntent();
                                        intent.putExtra("PHONE",phone);
                                        intent.putExtra("PAW",pwd);
                                        setResult(SIGN_IN_RESULT_CODE,intent);
                                        finish();
                                    }else if(type == USER_MD_PASSWD){
                                        //忘记密码
                                        SnackbarHelp.showSnackbarMsg(UserSignUpPassWdActivity.this,resultJsonObject.optString("msg"));
                                    }else  if(type == USER_MD_VIP_CARD){
                                      //重置卡密码
                                        SnackbarHelp.showSnackbarMsg(UserSignUpPassWdActivity.this,resultJsonObject.optString("msg"));
                                    }

                                }catch (JSONException e){
                                    SnackbarHelp. showSnackbarMsg(UserSignUpPassWdActivity.this,getResources().getString(R.string.error_parser_json));
                                }
                            }
                        }
                    }
                });

    }

    @Override
    public void onBackPressed() {
        if(depth==0){
            super.onBackPressed();
        }else if(depth == 1){
            depth--;
            translationX(mViewStep01,0,SCREEN_WIDTH);
            translationX(mViewStep00,-SCREEN_WIDTH,0);
        }else if(depth == 2){
            depth--;
            translationX(mViewStep02,0,SCREEN_WIDTH);
            translationX(mViewStep01,-SCREEN_WIDTH,0);
        }
    }

    private  final static class RerHandler extends Handler {

        private final WeakReference<TextView> mTextViewRef;
        private final WeakReference<Timer> mTimer;
        public RerHandler(TextView textView,Timer timer){
            mTextViewRef = new WeakReference<TextView>(textView);
            mTimer = new WeakReference<Timer>(timer);
        }

        @Override
        public void handleMessage(Message msg) {
            TextView mtextView  = mTextViewRef.get();
            Timer mtimer = mTimer.get();
            if(mtextView==null||mtimer==null)return ;
            switch (msg.what) {
                case 1:
                    _timerCount--;
                    mtextView.setText(_timerCount.toString());
                    if(_timerCount == 0){
                        mtextView.setEnabled(true);
                        mtextView.setText("发送");
                        mtimer.cancel();
                    }
                    break;
                case 0:
                    mtimer.cancel();
                    mtextView.setEnabled(true);
                    mtextView.setText("发送");
                    break;
            }
        }
    }

    private void timerStart() {
        time.setEnabled(false);
        _timerCount = 60;
        _timer=new Timer();
        _timerHandler = new RerHandler(time, _timer);
        _timer.schedule(new TimerTask() {
            public void run() {
                Message message = _timerHandler.obtainMessage();
                message.what = 1;
                _timerHandler.sendMessage(message);
            }
        }, 10, 1000);
    }

    @Override
    protected void onDestroy() {
        if(_timerHandler!=null){
            _timerHandler.removeMessages(0);
            _timerHandler.removeMessages(1);
        }
        if(_timer!=null){
            _timer.cancel();
        }
        smsid = null;
        super.onDestroy();
    }
}
